const Koa = require("koa");
const _ = require("lodash");
const path = require("path");
const util = require("util");
const moment = require("moment");
const cors = require("koa-cors");
const helmet = require("koa-helmet");
const convert = require("koa-convert");
const axios = require("axios");
const address = require("address");
const getMac = util.promisify(address.mac);

const model = require("./model");
const redis = require("./redis");
const config = require("./config");
const router = require("./router");
const pkg = require("./package.json");

// 中间件
const logger = require("./middleware/logger");
const auth = require("./middleware/auth");
const compat = require("./middleware/compat");
const xml = require("./middleware/xml");
const body = require("./middleware/body");
const error = require("./middleware/error");
const context = require("./middleware/context");

// 初始化
const app = new Koa();
const mysql = model.getModels(config.mysql);

// 全局
global.BaaS = {};
global.BaaS.router = router;
global.BaaS.bookshelf = mysql.bookshelf;
global.BaaS.bookshelfs = {};
global.BaaS.getBookshelf = model.getBookshelf;
global.BaaS.getModels = model.getModels;
global.BaaS.Models = mysql.Models;
global.BaaS.redis = redis;

// 中间件
app.use(compat());
app.use(helmet());
app.use(convert(cors({ credentials: true, origin: true })));
app.use(logger());
app.use(async (ctx, next) => {
    console.log(ctx.headers);
    await next();
});
app.use(xml());
app.use(body({ multipart: true }));
app.use(context());
app.use(error());
app.use(auth());
app.use(router.routes());
app.use(router.allowedMethods());

// 启动
(async () => {
  // 检测mac地址
  const macAddress = await getMac();
  if (config.checkMac) {
    const checkDevice = await axios({
      method: "get",
      url: `https://baas.qingful.com/2.0/class/public/table/device/fetch?where=mac,${macAddress}&where=status,1`,
      headers: {
        "x-qingful-appid": "399813461509",
        "x-qingful-appkey": "a6f23850-f063-11e7-86f6-1d2cc82858b1"
      }
    }).catch(err => {
      throw new Error("System Networking Failed");
    });
    if (!checkDevice.data.data) {
      throw new Error(`System Startup Failed, Mac Address ${macAddress}`);
    }
  }

  app.listen(config.port, async () => {
    const date = moment().format("YYYY-MM-DD HH:mm:ss");
    console.log(`[${date}] [BaaS] Version: ${pkg.version}`);
    console.log(`[${date}] [BaaS] Mac: ${macAddress}`);
    console.log(`[${date}] [BaaS] Website: https://2.0.baas.qingful.com`);
    console.log(`[${date}] [BaaS] Nodejs Version: ${process.version}`);
    console.log(
      `[${date}] [BaaS] Nodejs Platform: ${process.platform} ${process.arch}`
    );
    console.log(`[${date}] [BaaS] Server Enviroment: ${app.env}`);
    console.log(
      `[${date}] [BaaS] Server running at: http://127.0.0.1:${config.port}`
    );
  });
})();
